﻿#if UNITY_EDITOR

using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using Core;

public static class UIToolEditor
{
    [InitializeOnLoadMethod]
    private static void Init()
    {
        EditorApplication.hierarchyChanged -= EditorApplication_hierarchyChanged;
        EditorApplication.hierarchyChanged += EditorApplication_hierarchyChanged;
    }

    static void EditorApplication_hierarchyChanged()
    {
        if (Selection.activeGameObject == null)
            return;

        var isDirty = false;
        
        if (CheckEx<Image, ImageEx>(Selection.activeGameObject))
            isDirty = true;

        if (CheckEx<RawImage, RawImageEx>(Selection.activeGameObject))
            isDirty = true;

        if (CheckEx<Button, ButtonEx>(Selection.activeGameObject))
            isDirty = true;

        if (isDirty)
            EditorUtility.SetDirty(Selection.activeGameObject);
    }

    static bool CheckEx<UIType, UIExType>(GameObject select) 
        where UIType : UnityEngine.Component
        where UIExType : BaseUI
    {
        if (select.GetComponent<UIType>())
        {
            if (!select.GetComponent<UIExType>())
            {
                select.AddComponent<UIExType>();
                return true;
            }
        }
        else
        {
            var ex = select.GetComponent<UIExType>();
            if (ex != null)
            {
                GameObject.DestroyImmediate(ex);
                return true;
            }
        }

        return false;
    }
}

#endif